<?php

namespace app\admin\controller;

use think\Controller;
use think\captcha\Captcha;
use think\Validate;
use Config;
use app\common\controller\Common;
use Env;
use think\Db;
use app\admin\model\Admin as AdminModel;

class Login extends Common
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function index()
    {
        if ($this->check_admin_login()) {
            $this->redirect('admin/index/index');
        }
        return $this->fetch();
    }

    // 必须是Ajax的请求验证
    public function login()
    {
        if(!request()->isAjax()){
            $this->error("提交方式错误！",url('admin/login/index'));
        } else {
            $username = input('username');
            $password = input('password');
            $rememberme = input('rememberme');
            
            $validate = Validate::make([
                'username' => 'require|max:50|min:1',
                'password' => 'require|max:50|min:3'
            ]);                        
            $rst   = $validate->check(array('username'=>$username,'password'=>$password));
            if(true != $rst) {                
                $this->error($validate->getError(), url('admin/login/index'));
            }
                        
            $username="123";
            $admin = new AdminModel;
            if($admin->login($username, $password, "123")) {
                // var_dump("success");
                $this->success('登陆成功', url('admin/index/index'));
            } else {
                $this->error($admin->getError(), url('admin/login/index'));
            }
            // $db = DBUtil::connect_admin();
            // $userinfo = $db->table('admin_user')->where('username', $username)->find();            
            // // if(encrypt_password($password, $userinfo['salt']) != $userinfo['password']) {
            // //     $this->error('用户名名或者密码错误');
            // // }
            // if($userinfo['is_disabled'] > 0) {
            //     $this->error('账号被禁用');
            // }
            // $update_date =['last_login_time'   => time(), 
            //                 'last_login_ip'     => request()->ip(), 
            //                 'login_count'       => $userinfo['login_count'] + 1
            //     ];
            // $db->table('admin_user')->where('username', $username)->data($update_date)->update();
            // session('uid', $userinfo['id']);
            // session('user', $userinfo);

            //TODO 记录登陆日志
            // $this->success('登陆成功', url('admin/index/index'));
            // $this->redirect('admin/index/index'); 
        }       
    }
}
